# Simple AJAX chess website - Chat related handlers
#
# Copyright (C) 2008  Hong Anh Khoa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from google.appengine.api import users

from basehandler import BaseRequestHandler
from datamodel import *

from datetime import *
import time

class ChatHandler(BaseRequestHandler):
  
  def get(self, roomid):
    room = Room.get(roomid)
    
    # Get request values
    ltime = datetime.fromtimestamp(float(self.request.get("time")))
    
    # Get chats from last time
    chats = Chat.gql("WHERE sent>:1 AND room=:2", ltime, room)
    
    # If no chats from last time
    if chats.count() == 0:
      self.response.out.write("0|")
      return
    
    # Update time = last chat sent time
    ltime = int(time.mktime(chats[chats.count() - 1].sent.timetuple())) + 1
    
    # Build the response
    content = self.generate("chats.tpl.html", {'chats': chats, 'time': ltime})
    self.response.out.write(content)
    
  def post(self, roomid):
  
    # Get request values
    user = users.get_current_user()
    content = self.request.get("content")
    
    # Save the chat content to the datastore
    chat = Chat(author = user,
                room = Room.get(roomid),
                content = content)
    chat.put()
    
